<?php
/**
 * Created by PhpStorm.
 * User: qishengqiang
 * Date: 2022-09-26
 * Time: 03:51
 */

namespace app\services;


use app\models\WxMessageRecords;
use app\models\Wxprograms;
use GuzzleHttp\Client;
use think\facade\Cache;

class WxService extends ServiceBase
{
    public function getAccessToken()
    {
        try {
            $accessToken = Cache::get('accessToken', '');

            if (!$accessToken) {
                $config = Wxprograms::find(1);
                $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$config->appId.'&secret='.$config->appSecret;
                $client = new Client();

                $res = $client->get($url);

                $data = json_decode($res->getBody()->__toString());

                if (isset($data->access_token) && $data->access_token != '') {
                    $accessToken = $data->access_token;
                    Cache::set('accessToken', $accessToken, 7200);
                } else {
                    throw new \Exception($data->errmsg, 500);
                }
            }

            return $accessToken;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    public function sendMessage(WxMessageRecords $record, $data)
    {
        try {
            $accessToken = $this->getAccessToken();

            $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$accessToken;
            $params = [
                'json' => json_decode($record->content)
            ];
            $client = new Client();

            $res = $client->post($url, $params);

            $data = json_decode($res->getBody()->__toString());

            $record->status = 1;
            $record->errcode = $data->errcode;
            $record->errmsg = $data->errmsg;
            $record->save();

        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }

    }
}